﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Text;
using System.Windows.Forms;
using UCL.Forms;

namespace DBKit5
{
    public partial class frmGenerateVarTemplate : Form
    {
        public string TableName { get; set; }
        public XElement DataTable { get; set; }
        public frmGenerateVarTemplate()
        {
            InitializeComponent();
        }

        private void frmGenerateVarTemplate_Load(object sender, EventArgs e)
        {
            this.Text = "生成SQL数据模板 - " + TableName;
            if (DataTable != null)
            {
                foreach(XElement xe in DataTable.Elements())
                {
                    tbFields.AppendText(string.Format("{0} | ", xe.Attribute("Name").Value));
                }
            }

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (tbResult.TextLength == 0) return;
            this.ShowSaveFileDialog("Text files (*.txt)|*.txt", fn => { System.IO.File.WriteAllText(fn, tbResult.Text); return "success"; });
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            if (tbFmtSql.TextLength == 0 || tbFields.TextLength==0 || DataTable == null) return;
            tbResult.Clear();
            string[] arrColumns = tbFields.Text.Split(" | ".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
            XElement col;
            foreach (string f in arrColumns)
            {
                col = DataTable.XPathSelectElement(string.Format("field[@Name='{0}']",f));
                tbResult.AppendText(string.Format(tbFmtSql.Text, f, (col==null?"?":col.Attribute("Type").Value),f.ToLower(),f.ToUpper()));
                tbResult.AppendText(Environment.NewLine);
            }
        }
    }
}
